const mongoose =require('mongoose')
const Movie = mongoose.model('Movie')

const qiniu = require('qiniu')
const nanoid = require('nanoid')
const config = require('../config')

const bucket = config.qiniu.bucket
const mac = new qiniu.auth.digest.Mac(config.qiniu.AK, config.qiniu.SK)
const cfg = new qiniu.conf.Config()
const client = new qiniu.rs.BucketManager(mac, cfg) // 配置七牛擅闯

const uploadToQinniu = async (url, key) => {
  return new Promise((resolve, reject) => {
    // 调用 fetch方法给 资源重命名(key)
    client.fetch(url, bucket, key, (err, ret, info) => {
      if (err) {
        reject(err)
      } else {
        if (info.statusCode == 200) {
          resolve({key})
        } else {
          reject(info)
        }
      }
    })
  })
}

;(async () => {
  // 查找数据
  let movies = await Movie.find({
    $or: [
      { videoKey: { $exists: false } },
      { videoKey: null },
      { videoKey: '' }
    ]
  })

  for (let i = 0; i < movies.length; i++) {
    console.log(`${i}/${movies.length}`)
    let movie = movies[i]

    if ( movie.video && !movie.videoKey ){
      try {
        console.log('video')
        let videoData = await uploadToQinniu(movie.video, nanoid() + '.mp4')
        console.log('png')
        let coverData = await uploadToQinniu(movie.cover, nanoid() + '.png')
        console.log('png')        
        let posterData = await uploadToQinniu(movie.poster, nanoid() + '.png')

        if (videoData.key) {
          movie.videoKey = videoData.key
        }
        if (coverData.key) {
          movie.coverKey = coverData.key
        }
        if (posterData.key) {
          movie.posterKey = posterData.key
        } 

       await movie.save()
      } catch(err) {
        throw err
      }
    }
  }
} )()

/*
{ video:
   'http://vt1.doubanio.com/201906291720/24c7ee30447ca65ae861f8f8f6628d78/view/movie/M/402480749.mp4',
  doubanId: 26931786,
  cover:
   'https://img3.doubanio.com/img/trailer/medium/2560046305.jpg?1560949911',
  poster:
   'https://img3.doubanio.com/view/photo/l_ratio_poster/public/p2558293106.jpg',
  videoKey: 'ptuu7gzoh.bkt.clouddn.com/o_HY4lPsbtcY2o5I2THl6.mp4',
  coverKey: 'ptuu7gzoh.bkt.clouddn.com/ZKUx7shK3NW5J6w8EYdLI.png',
  posterKey: 'ptuu7gzoh.bkt.clouddn.com/M7gQunrRoxXBFDL-L00pt.png' }
*/